package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet(urlPatterns = "/consoleQueryTimeServerRoleCreate")
public class ConsoleQueryTimeServerRoleCreate extends BaseJsonHttpServlet {

	private static Logger logger = LogManager.getLogger(ConsoleQueryTimeServerRoleCreate.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("request consoleQueryTimeServerRoleCreate");
		HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
		JSONObject paramObj = httpJsonWebParam.getParamObj();
		String serverList;
		try{
			serverList = paramObj.getString("serverList");
		}catch (Exception e){
			logger.error("consoleQueryTimeServerRoleCreate argument error:" + e);
			sendResult(response, 0, "argument error");
			return;
		}
		JSONObject resultObj = new JSONObject();
		List<Long> serverIdList = StringUtils.stringToLongList(serverList, ",");
		for (long serverId : serverIdList) {
			ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
			if (serverInfo == null) {
				continue;
			}

			String serverData = "";
			try {
				serverData = HttpHelper.doPostJsonTimeOut(serverInfo.getWebServerUrl() + "/queryTimeServerRoleCreate", paramObj.toJSONString(), "UTF-8", new HashMap<>());
				JSONObject jsonObj = JSONObject.parseObject(serverData);
				if(null != jsonObj) {
					JSONObject dataObj = jsonObj.getJSONObject("" + serverId);
					if (null != dataObj) {
						resultObj.put("" + serverId, dataObj);
					}
				}
			} catch (Exception ex) {
				logger.error("json parse error,{},error:", serverData, ex);
			}

		}
		sendMessage(response, resultObj.toJSONString());
	}

}
